<script setup>
import {computed, reactive, ref, toRaw} from 'vue'
import {getCode, login, menuPermissions, userAuthentication} from "../../api/index.js";
import {Lock, UserFilled} from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";
import {useRoute} from "vue-router";
import {useStore} from 'vuex'
const store = useStore()
const formType = ref(0)
const imgUrl = new URL('/public/login-head.png',import.meta.url).href;
const router = useRouter()
const routerList = computed(()=>store.state.menu.routerList)
const handleChange = ()=>{
    formType.value = formType.value?0:1;
}
const loginForm = reactive({
  userName:'',
  passWord:'',
  validCode:'',
})
//发送短信
const countdown = reactive({
  validText:'获取验证码',
  time:60
})
let flag = false
const countdownChange = ()=>{
  if(flag){
    return ;
  }
  const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
  if(!loginForm.userName||!phoneReg.test(loginForm.userName)){
      return ElMessage({
        message:"请检查手机号是否正确",
        type:"warning"
      })
  }
  const time = setInterval(()=>{
      if(countdown.time<=0){
        countdown.time = 60
        countdown.validText = '获取验证码'
        flag = false
        //如果不清除，会导致倒计时 “重置后又自动开始”，完全不符合 “倒计时结束后可重新点击” 的业务预期
        clearInterval(time)
      }else{
        countdown.time-=1;
        countdown.validText = `剩余${countdown.time}秒`
      }
    },1000)
  flag = true
  getCode({tel:loginForm.userName}).then((data)=>{
    // console.log(data,'data')
    if(data.data.code===10000){
      ElMessage.success('发送成功');
      console.log('发送成功了！！！')
    }else{
      console.log('发送失败了！！！')
    }
  })
}
const validateUser = (rule,value,callback)=>{
  if(value===''){
    callback(new Error('请输入账号'))
  }else{
    const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
    phoneReg.test(value)?callback():callback(new Error('手机号格式不对，请输入正确手机号'))
  }
}
const validatePass = (rule,value,callback)=>{
    if(value===''){
      callback(new Error('请输入密码'))
    }else{
      const reg = /^[a-zA-Z0-9_-]{4,16}$/
      reg.test(value)?callback():callback(new Error('密码格式不对，需要4到16位字符,请确认格式'))
    }
}
const rules = reactive({
  userName:[{
    validator:validateUser,
    trigger:'blur'
  }],
  passWord:[{
    validator:validatePass,
    trigger:'blur'
  }]
})
const loginFormRef = ref()
const submitForm = async (formEl)=>{
  if(!formEl){
    return ;
  }
  await formEl.validate((valid,fields)=>{
    if(valid){
      console.log(loginForm,'submit!')
      //注册页面
      if(formType.value){
        userAuthentication(loginForm).then(({data})=>{
          if(data.code===10000){
              ElMessage.success('注册成功，请登录');
              formType.value = 0
          }
        })
        //登录页面
      }else{
        login(loginForm).then(({data})=>{
          if(data.code===10000){
            ElMessage.success("登录成功")
            console.log('data',data)
            //用localStorage缓存用户信息
            localStorage.setItem('pz_token',data.data.token)
            //如果尝试存入非字符串数据（如对象、数组、数字等），localStorage 会自动将其转为 [object Object] 这类无意义的字符串，导致数据丢失或无法正常读取。
            localStorage.setItem('pz_userInfo',JSON.stringify(data.data.userInfo))
            // router.push("/")
            menuPermissions().then(({data})=>{
                store.commit("dynamicMenu",data.data)
                console.log(routerList,'routerList')
              toRaw(routerList.value).forEach(item=>{
                  router.addRoute('main',item)
              })
              router.push("/")
            })
          }
        })
      }
    }else{
      console.log('error submit!',fields)
    }
  })
}
</script>

<template>
<!--  v-bind 内部的内容会被 Vue 当作 “JavaScript 表达式” 解析，而不是直接的字符串。-->
<!--  还是使用放映机的类比，我们的子组件通过 myUser 对象将其用户字符串的值传递给父组件。它在父组件上投射到的墙就被称为‘slotProps’。-->
    <el-row class="login-container" justify="center" :align='"middle"'>
      <el-card style="max-width:480px">
        <template #header>
          <div class="card-header">
            <img :src="imgUrl" alt="">
          </div>
        </template>
        <div class="jump-link">
          <el-link type="primary" @click="handleChange">{{formType?'返回登录':'注册账号'}}</el-link>
        </div>
        <el-form :model="loginForm"
        ref="loginFormRef"
        style="max-width:600px"
        class="demo-ruleForm"
        :rules="rules">
          <el-form-item prop="userName">
            <el-input v-model="loginForm.userName" placeholder="手机号" :prefix-icon="UserFilled"></el-input>
          </el-form-item>
          <el-form-item prop="passWord">
            <el-input v-model="loginForm.passWord" type="password" placeholder="密码" :prefix-icon="Lock"></el-input>
          </el-form-item>
          <el-form-item prop="validCode" v-if="formType===1">
            <el-input v-model="loginForm.validCode" placeholder="验证码" :prefix-icon="Lock">
              <template #append>
                <span @click="countdownChange">{{countdown.validText}}</span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
              <el-button type="primary" :style="{width:'100%'}" @click="submitForm(loginFormRef)">
                {{formType?"注册账号":"登录"}}
              </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-row>
</template>

<style lang="less" scoped>
:deep(.el-card__header) {
  padding: 0
}
.login-container {
  height: 100%;
  .card-header{
    background-color: #899fe1;
    img {
      width: 430px;
    }
  }
  .jump-link {
    text-align: right;
    margin-bottom: 10px;
  }
}

</style>